package socket.before;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) throws Exception, Exception {
	      //为了简单起见，所有的异常信息都往外抛  
	      int port = 8989;  
	      //定义一个ServerSocket监听在端口8989上  
	      ServerSocket server = new ServerSocket(port);  
	      //server尝试接收其他Socket的连接请求，server的accept方法是阻塞式的  
	      Socket socket = server.accept();  
	      //跟客户端建立好连接之后，我们就可以获取socket的InputStream，并从中读取客户端发过来的信息了。  
	      Reader reader = new InputStreamReader(socket.getInputStream());  
	      char chars[] = new char[64];  
	      int len;  
	      StringBuilder sb = new StringBuilder();  
	      String temp;  
	      int index;  
	      while ((len=reader.read(chars)) != -1) {  
	         temp = new String(chars, 0, len);  
	         if ((index = temp.indexOf("eof")) != -1) {//遇到eof时就结束接收  
	            sb.append(temp.substring(0, index));  
	            break;  
	         }  
	         sb.append(temp);  
	      }  
	      System.out.println("from client: " + sb);  
	      //读完后写一句  
	      Writer writer = new OutputStreamWriter(socket.getOutputStream());  
	      writer.write("Hello Client.");
	      socket.shutdownOutput();
	      writer.flush();  
	      writer.close();  
	      reader.close();  
	      socket.close();  
	      server.close();

	}

	public static void t1() throws IOException {
		ServerSocket ss = new ServerSocket(8989);
		Socket socket = ss.accept();
		if (socket != null) {
			ServeDemo sd = new ServeDemo(socket);
			Thread th = new Thread(sd);
			th.start();
		}
	}

}

class ServeDemo implements Runnable {
	private Socket socket;

	public ServeDemo(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					this.socket.getInputStream()));
			System.out.println(br.readLine());
			OutputStream out = socket.getOutputStream();
			out.write("Hi client".getBytes());
			out.flush();
			// out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
